﻿using Crm.Manager.Common;
using LeHouse.Server.Dto;
using LeHouse.Server.Service;
using LeHouse.Server.WebApi.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;

namespace LeHouse.Server.WebApi.Controllers
{
    public class LoginController : ApiController
    {
        [HttpGet]
        public bool Get()
        {
            return true;
        }
        /// <summary>
        /// 验证码
        /// </summary>
        /// <returns></returns>
        [Route("api/Login/GetCodeImg")]
        public dynamic GetCodeImg()
        {
            string code = string.Empty;
            byte[] imgByte = ValidateCode.CreateValidateGraphic(out code, 4, 100, 40, 20);
            return new
            {
                code = code.ToLower(),
                imgByte = imgByte
            };
        }

        [HttpPost]
        [Route("api/Login/GetLogin")]
        public dynamic GetLogin([FromBody]LoginUser lu)
        {
            //1.判断验证
            if (string.IsNullOrEmpty(lu.T_Account) || string.IsNullOrEmpty(lu.T_Password))
            {
                return new
                {
                    state = false,
                    message = "账号密码不能为空！"
                };
            }
            //2.登录验证
            System_StaffService staff = new System_StaffService();
            System_RoleStaffService role = new System_RoleStaffService();
            System_DeptStaffService dept = new System_DeptStaffService();
            System_Staff sf = staff.Select(t => t.T_Account == lu.T_Account).FirstOrDefault();

            if (sf == null || sf.T_StaffID < 0)
            {
                return new
                {
                    state = false,
                    message = "账号不存在！"
                };
            }
            if (sf.T_Password != lu.T_Password)
            {
                return new
                {
                    state = false,
                    message = "密码错误！"
                };
            }

            if (sf.T_State == Convert.ToInt32(EnumState.StateNO))
            {
                return new
                {
                    state = false,
                    message = "账号已经被冻结，请联系管理员！"
                };
            }
            //获取角色部门权限
            sf.T_Department = dept.Select(t => t.T_StaffID == sf.T_StaffID).Select(t => t.T_DepartmentID).ToArray();
            sf.T_Role = role.Select(t => t.T_StaffID == sf.T_StaffID).Select(t => t.T_RoleID).ToArray();

            string deptStr = string.Join(",", sf.T_Department);
            string roleStr = string.Join(",", sf.T_Role);

            //3.验证成功，生成JWT
            var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var now = Math.Round((DateTime.UtcNow.AddMinutes(10) - unixEpoch).TotalSeconds);            var payload = new Dictionary<string, object>()
                        {
                            {"exp", now },
                            {"id",sf.T_StaffID}//将用户Id返回客户端
                        };
            var secretKey = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";
            string token = JWT.JsonWebToken.Encode(payload, secretKey, JWT.JwtHashAlgorithm.HS256);
            if (sf.T_IsSystem == 1)
            {
                return new
                {

                    token = token,
                    userid = sf.T_StaffID,
                    account = sf.T_Account,
                    name = sf.T_Name,
                    pwd = sf.T_Password,
                    dept = deptStr == "" ? "1000" : deptStr,
                    role = roleStr == "" ? "1000" : roleStr,
                    state = true,
                    message = "ok"
                };
            }
            else
            {
                return new
                {

                    token = token,
                    userid = sf.T_StaffID,
                    account = sf.T_Account,
                    name = sf.T_Name,
                    pwd = sf.T_Password,
                    dept = "2000",
                    role = "2000",
                    state = true,
                    message = "ok"
                };
            }
        }

    }
}
